<?php
/**
 * 管理元后台
 * User: huyi
 * Date: 2018/9/29
 * Time: 9:53
 */
namespace app\Admin\controller;

use app\api\controller\Upload;
use app\common\controller\AdminBase;
use app\common\controller\CommonShare;
use think\Controller;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\Request;

class Admin extends AdminBase{
    private $ude = array();

    public function index(){
        $teachers = Db::name('users')->where(array('usertype' => 2))->paginate(10);
        $page     = $teachers->render();
        $this->assign('page', $page);
        return $this->fetch('index', array('admin_user_list' => $teachers));
    }

    public function add(){
        return $this->fetch('add');
    }

    public function save(Request $request){
        $data = $request->post();
        if($data['userPassword'] != $data['confirm_password']){
            return json(array('code' => 0, 'msg' => '密码不一致！'));
        }
        if(strlen($data['userPassword']) < 6 || strlen($data['userPassword']) > 15){
            return json(array('code' => 0, 'msg' => '密码长度必须在6-15位之间！'));
        }
        if(trim($data['userPassword']) == '' || trim($data['userLoginName']) == '' || trim($data['name']) == '' || trim($data['male'] == '')){
            return json(array('code' => 0, 'msg' => '*是必填项！'));
        }
        //入库 本地库bhmd5
        unset($data['confirm_password']);
        $data['usertype']     = 2; //表示教师
        $register             = new CommonShare();
        $result               = $register->register($data);
        $data['userPassword'] = bhmd5(trim($data['userPassword']));
        if($result === true){
            $r = 0;
            try{
                $r = Db::name('users')->insertGetId($data);
            }
            catch(Exception $e){
                Db::name('users')->where('id', $r)->update($data);
                $this->success('添加成功~~');
            }
            if($r > 0){
                //take data to origin system  interface
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }
        $this->error('添加失败');
    }

    public function delete(){
        $id  = input('id');
        $res = Db::name('users')->where('id', $id)->delete();
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    public function backInfo(){
        $config = Config::get('AdminUser');
        return json($config);
    }

    public function upload(){
        //上传
        if(!empty($_FILES)){
            $files = request()->file('teachers');
            if(empty($files)){
                $this->error("请选择要导入的excel文件");
            }
            $upload_path = str_replace('\\', '/', ROOT_PATH . '/public/uploads');
            $info        = $files->move($upload_path);
            if($info){
                $excel     = new \PHPExcel();
                $file_name = $upload_path . '/' . $info->getSaveName();
                $ext       = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                if($ext == 'xlsx'){
                    $boj      = \PHPExcel_IOFactory::createReader('Excel2007');
                    $objexcel = $boj->load($file_name, $encode = 'utf-8');
                }elseif($ext == 'xls'){
                    $boj      = \PHPExcel_IOFactory::createReader('Excel5');
                    $objexcel = $boj->load($file_name, $encode = 'utf-8');
                }

                $sheet = $objexcel->getSheet(0);
                //行数
                $hight = $sheet->getHighestRow();
                //列数
                $column = $sheet->getHighestColumn();

                for($rowIndex = 1; $rowIndex <= $hight; $rowIndex++){
                    for($colIndex = "A"; $colIndex <= $column; $colIndex++){
                        $location = $colIndex . $rowIndex;

                        $cell = $sheet->getCell($location)->getValue();

                        if($cell instanceof \PHPExcel_RichText){ // 富文本转换字符串
                            $cell = $cell->__toString();
                        }

                        $dataExcel[$rowIndex][$colIndex] = $cell;
                    }
                }

                $r              = ["status" => 1, "info" => "文件内容获取成功"];
                $r["data"]      = $dataExcel;
                $r["allRow"]    = $hight;
                $r["allColumn"] = $column;
                if($r['status'] == 1){
                    if(isset($r['data'][2])){
                        array_shift($r['data']);
                        $res = $this->upOnline($r['data']);
                        if($res == 1){
                            $this->success("导入成功");
                        }else{
                            $this->error("导入失败");
                        }
                    }else{
                        $this->error("导入失败,请填写数据");
                    }
                }else{
                    $this->error("导入失败");
                }
            }
        }else{
            $this->error("请选择要导入的excel文件");
        }
    }

    public function upOnline($data){
        $re = $this->checkExcel($data);
        foreach($this->ude as $kk){
            unset($data[$kk]);
        }
        if($re === false){
            $this->error("导入失败,请把必填数据填写");
        }
        $arr   = array();
        $array = array();
        $r     = true;
        foreach($data as $k => $v){
            $arr['userLoginName'] = $v['A'];
            $arr['userPassword']  = $v['B'];
            $arr['name']          = $v['C'];
            $arr['male']          = $v['D'];
            $arr['mobile']        = $v['E'];
            $arr['address']       = $v['F'];
            $arr['company']       = $v['G'];
            $arr['country']       = $v['H'];
            $arr['description']   = $v['I'];
            $register             = new CommonShare();
            $r                    = $register->register($arr, 'batch');
            $arr['male']          = $v['D'] == '男' ? 'true' : 'false';
            $arr['userPassword']  = bhmd5($v['B']);
            $arr['usertype']      = 2;
            $array[]              = $arr;

            $rr = Db::name('users')->where('userLoginName', $arr['userLoginName'])->find();
            if($rr){
                Db::name('users')->where('userLoginName', $arr['userLoginName'])->update($arr);
            }else{
                Db::name('users')->insert($arr);
            }
        }
        $this->success('添加成功');
    }

    public function checkExcel($data){
        $check = true;
        foreach($data as $k => $v){
            if(empty(trim($v['A'])) && empty(trim($v['B'])) && empty(trim($v['C'])) && empty(trim($v['D']))){
                $this->ude[] = $k;
                continue;
            }
            if(empty(trim($v['A'])) || empty(trim($v['B'])) || empty(trim($v['C'])) || empty(trim($v['D']))){
                $check = false;
            }
        }
        return $check;
    }

    public function get_microtime(){
        list($usec, $sec) = explode(' ', microtime());
        return (float) $usec + (float) $sec;
    }

}